package org.restql.db.operation;

import java.io.PrintWriter;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.restql.webapp.RestQLException;
import org.restql.webapp.ReturnType;
import org.restql.db.resource.DatabaseResource;
import org.restql.db.resource.RequestResource;

public class DatabaseDtd extends DatabaseGet {

	private static Log logger = LogFactory.getLog(DatabaseDtd.class);

	public DatabaseDtd(DatabaseResource databaseResource, RequestResource requestResource) {
		super(databaseResource, requestResource);
	}

	public void executeSql(PrintWriter printer, ReturnType returnType, String show) throws RestQLException {
		try {
			String constructedSQL =this.databaseResource.getSelectString(requestResource, "1", null);

			// Execute SQL query
			PreparedStatement stmt;
				stmt = getConnection().prepareStatement(constructedSQL);


			logger.info("Executing: " + constructedSQL);

			ResultSet rs = stmt.executeQuery();
			Map<String, String> colTypes = getColInfo(rs);

			generateDtd(colTypes, printer);

		} catch (SQLException e) {
			e.printStackTrace();
			throw new RestQLException("Error doing query to get DTD", e);
		}
	}

	private void generateDtd(Map<String, String> colTypes, PrintWriter printer) {

		String fieldElements = "";
		String fieldList = "";
		for (String colName : colTypes.keySet()) {
			fieldElements += "\t<!ELEMENT " + colName + " (#PCDATA)>\n";
			fieldList += (fieldList.length() > 0 ? "," : "") + colName;
		}

		printer.println("<!DOCTYPE " + this.requestResource.getDbName() + "[");
		printer.println("\t<!ELEMENT " + this.requestResource.getResourceName() +
				" (" + fieldList + ")>");
		printer.println(fieldElements);
		printer.println("]>");
	}

}
